# coding: utf-8
import datetime
import json
from finance_c2c.urls import OutApiBaseUrl
from core.wchat.wx_base import WxBase
from finance_c2c.local_settings import ONLINE

wx_base = WxBase()


class ErrorMessageMiddleware(object):
    def process_response(self, request, response):
        if OutApiBaseUrl in request.path:
            if response.status_code == 400:
                code = 400
                error = ""
                if isinstance(response.data, list):
                    error = response.data[0]
                else:
                    for error in response.data.serializer.errors:
                        error = "%s" % response.data.serializer.errors[error][0]
                        break
                data = {"code": code, "message": error}
                content = json.dumps(data).encode("utf-8")
                content_length = len(content)
                response._headers["content-length"] = ('Content-Length', str(content_length))
                response.data = data
                response.content = content
            elif response.status_code == 500:
                data = {"code": response.status_code, "message": "系统错误，请联系管理员"}
                content = json.dumps(data).encode("utf-8")
                content_length = len(content)
                response._headers["content-length"] = ('Content-Length', str(content_length))
                response.data = data
                response.content = content
            elif response.status_code == 401 or response.status_code == 403:
                data = {"code": response.status_code, "message": response.data.get("detail")}
                content = json.dumps(data).encode("utf-8")
                content_length = len(content)
                response._headers["content-length"] = ('Content-Length', str(content_length))
                response.data = data
                response.content = content
        return response


class ErrorMiddleware(object):
    def process_exception(self, request, exception):
        if ONLINE:
            import traceback
            e = traceback.format_exc()
            now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(request.get_full_path(), request.POST, request.GET, e, now_time)
            user_id = "ojh4ptynBWEzmimzXxZFGtiOJAsY"
            content = "%s\n\n%s\n\n%s" % (now_time, request.get_full_path(), e)
            wx_base.client.message.send_text(user_id, content)


class DisableCSRF(object):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)


class LoggingMiddleware(object):
    def process_request(self, request):
        if not ONLINE:
            auth = request.META.get('HTTP_AUTHORIZATION', b'')

            print(request.path, "method:", request.method, "body", request.body, "GET:", request.GET, "POST:",
                  request.POST, "auth", auth)

    def process_response(self, request, response):
        if not ONLINE:
            print(response.status_code)
            # print(response.content, "response_content")
        return response
